package com.open.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.open.bean.OpenDict;
import com.open.result.OpenResult;
import com.open.service.OpenDictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author tanyongpeng
 * <p>des</p>
 **/
@RestController
@RequestMapping("/request/open")
@Slf4j
public class AdminDictController {


    @Autowired
    OpenDictService openDictService;

    @GetMapping("/admin/dict/list")
    public OpenResult list(@RequestParam Integer current,
                           @RequestParam Integer size,
                           @RequestParam(required = false) String dictDes,
                           @RequestParam(required = false) String dictCode){
        IPage<OpenDict> page = openDictService.page(new Page(current, size), new QueryWrapper<OpenDict>()
                .like(StrUtil.isNotBlank(dictDes), "dict_des", dictDes)
                .eq(StrUtil.isNotBlank(dictCode), "dict_code", dictCode).orderByDesc("did"));
        return OpenResult.success(page);
    }


    @GetMapping("/admin/dict/info/{id}")
    public OpenResult info(@PathVariable Integer id){
        return OpenResult.success(openDictService.getById(id));
    }

    @PostMapping("/admin/dict/save")
    public OpenResult save(@RequestBody OpenDict openDict){
        openDict.setCreateTime(new Date());
        openDict.setUpdateTime(new Date());
        OpenDict dict = openDictService.lambdaQuery().orderByDesc(OpenDict::getDid).last("limit 1").one();
        openDict.setDictCode(String.valueOf(Integer.parseInt(dict.getDictCode())+1));
        boolean save = openDictService.save(openDict);
        return OpenResult.save(save);
    }

    @PostMapping("/admin/dict/update")
    public OpenResult update(@RequestBody OpenDict openDict){
        boolean update = openDictService.lambdaUpdate()
                .set(OpenDict::getDictDes, openDict.getDictDes())
                .set(OpenDict::getDictValue, openDict.getDictValue())
                .set(OpenDict::getUpdateTime,new Date())
                .eq(OpenDict::getDid, openDict.getDid()).update();
        return OpenResult.update(update);
    }


    @GetMapping("/admin/dict/delete/{id}")
    public OpenResult delete(@PathVariable Integer id){
        boolean remove = openDictService.removeById(id);
        return OpenResult.delete(remove);
    }


}
